<template>
  <a-modal title="选择产品" :maskClosable="false" :visible="visible" @ok="close" @cancel="close" width="1200px" :footer="null">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24">
              <a-form-item label="名称">
                <a-input v-model="queryParam.materialName" placeholder="请输入名称"/>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24">
              <a-form-item label="料号">
                <a-input v-model="queryParam.materialCode" placeholder="请输入料号"/>
              </a-form-item>
            </a-col>

<!--            <a-col :md="8" :sm="24">-->
<!--              <a-form-item label="物料种类">-->
<!--                <a-select v-model="queryParam.materialType">-->
<!--                  <a-select-option :value="id" v-for="{id, name} in materialTypeList">-->
<!--                    {{ name }}-->
<!--                  </a-select-option>-->
<!--                </a-select>-->
<!--              </a-form-item>-->
<!--            </a-col>-->

            <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons"
                  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
            </span>
            </a-col>

          </a-row>
        </a-form>
      </div>

<!--      <div class="table-operator">-->
<!--        <a-button type="primary" @click="$refs.addForm.add({materialType: type})" icon="plus">新增</a-button>-->
<!--      </div>-->

      <s-table
        ref="table"
        size="default"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.materialId"
      >


        <span slot="action" slot-scope="text, record">
          <a @click="rowSelect(record)">选择</a>
        </span>
      </s-table>

      <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
        <img style="width: 100%" :src="previewImage"/>
      </a-modal>
      <add-form ref="addForm" @ok="handleOk"/>

    </a-card>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, del} from '@/api/modular/main/emsmaterial/emsMaterialManage'
import addForm from '../../emsmaterial/emsMaterialAddForm'
import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'
import { MATERIAL_TYPE_ENUM } from '@/utils/util'

export default {
  components: {
    STable,
    addForm,
  },
  props: {
    onRowSelected: {}
  },
  data() {
    return {
      visible: false,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      columns: [       // 表头
        {
          title: '序号', width:'80px',
          dataIndex: 'index',
          key: 'index',
          align: 'center',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '料号',
          dataIndex: 'materialCode'
        },
        {
          title: '名称',
          dataIndex: 'materialName'
        },
        {
          title: '规格',
          dataIndex: 'materialModelNumber'
        },
        {
          title: '图片',
          dataIndex: 'image',
          customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
        },
        {
          title: '库存数量',
          dataIndex: 'inventoryNumber'
        },
        {
          title: '预警值',
          dataIndex: 'inventoryWarningValue'
        },
        {
          title: '归属公司',
          dataIndex: 'orgIdCompanyName',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '80px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.queryParam = Object.assign(this.queryParam, this.record)
        this.queryParam.materialType = this.$businessEnum.MATERIAL_TYPE_ENUM.overseasProduct.id
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      previewVisible: false,
      previewImage: '',
      record: null,
    }
  },
  computed: {
    token() {
      return Vue.ls.get(ACCESS_TOKEN)
    },
    type() {
      // console.log(`computed type`)
      const materialTypeDictList = [
        {id: '1473944069297156097', value: '原料', code: 'material'},
        {id: '1473944318434619394', value: '成品', code: 'product'},
        {id: '1473944389062504450', value: '线缆', code: 'cable'},
        {id: '1473944715475824641', value: '包材', code: 'packing'},
      ]
      let routePath = this.$route.path
      let indexOfQuestionMark = routePath.indexOf('?')
      let param = routePath.substring(indexOfQuestionMark)
      let typeMap = param.split('=')
      let typeCode = typeMap[1] || 'material'
      let type = materialTypeDictList.find((dict) => dict.code == typeCode)
      return type || materialTypeDictList[0]
    },
    materialTypeList() {
      return [MATERIAL_TYPE_ENUM.overseasProduct]
    }
  },
  watch: {
    type() {
      if (this.$refs.table) {
        setTimeout(() => {
          this.$refs.table.refresh()
        }, 100)
      }
    }
  },
  methods: {
    show(record) {
      this.visible = true
      this.record = record
      setTimeout(() => {
        this.handleOk()
      }, 100)
    },
    close() {
      this.visible = false
      // this.$emit('ok', )
    },
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    imageURLFormat(text) {
      return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
    },
    preview(url) {
      this.previewVisible = true
      this.previewImage = url
    },
    rowSelect(row) {
      if (this.onRowSelected) {
        this.onRowSelected(JSON.parse(JSON.stringify(row)))
      }
      this.visible = false
    }
  },
  created() {
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}

.table-image {
  cursor: pointer;
  max-width: 100px;
  max-height: 50px;
  border: solid 1px #cccccc;
}
</style>
